<template>
  <div>
    <el-dialog
      :title="mode==='add'?'新增规则':'编辑规则'"
      :visible.sync="dialogVisible"
      width="750px"
      :close-on-click-modal="false"
      @close="close"
    >
      <el-form
        ref="form"
        v-loading="loading"
        :model="form"
        :rules="rules"
        label-suffix="："
        label-width="100px"
        size="small"
      >
        <div v-if="productInfo">
          <el-form-item label="当前房型">
            <span>{{ productInfo.name }}</span>
          </el-form-item>
          <el-form-item v-if="productInfo.productType==1||productInfo.productType==2" label="可用时段">
            <span v-if="productInfo.weekdayLimit">
              <span v-for="(item,index) in weekOptions" :key="index">
                <span v-if="productInfo.weekdayLimit.split(',').includes(item.value)">{{ item.label }}</span>
              </span>
            </span>
            <span v-else>无限制</span>
          </el-form-item>
          <el-form-item v-if="productInfo.productType==1||productInfo.productType==2" label="可用时间">
            <span
              v-if="productInfo.periodStartTime||productInfo.periodEndTime"
            >{{ productInfo.periodStartTime|minsToHourMins }}~{{ productInfo.periodEndTime|minsToHourMins }}</span>
            <span v-else>00:00~24:00</span>
          </el-form-item>
          <el-form-item label="基础价格">
            <span>{{ productInfo.basePrice/100 }}</span>
          </el-form-item>
        </div>

        <el-form-item label="规则名称" prop="name">
          <el-input v-model.trim="form.name" style="width:350px" maxlength="30" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="生效日期" prop="customEffectiveDay">
          <el-date-picker
            v-model="form.customEffectiveDay"
            size="small"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            format="yyyy-MM-dd"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item label="价格" prop="priceRuleValue">
          <el-input v-model.trim="form.priceRuleValue" style="width:350px" placeholder="请输入价格">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>

        <el-form-item label="规则" prop="dayRule">
          <el-radio-group v-model="form.dayRule">
            <div>
              <el-radio :label="1">指定每周日期</el-radio>
            </div>
            <div v-if="form.dayRule===1" class="nest-card-box">
              <el-card>
                <el-form-item prop="customActiveWeekDays">
                  <el-checkbox-group v-model="form.customActiveWeekDays">
                    <el-checkbox-button
                      v-for="(weekItem,weekIndex) in weekOptions"
                      :key="weekIndex"
                      :label="weekItem.value"
                      disable
                    >{{ weekItem.label }}</el-checkbox-button>
                  </el-checkbox-group>
                </el-form-item>
                <el-tag>设置规则指定日期仅在资源的可用日期内生效</el-tag>
              </el-card>
            </div>
            <div>
              <el-radio :label="0">指定每月日期</el-radio>
            </div>
            <div v-if="form.dayRule===0" class="nest-card-box">
              <el-card>
                <el-form-item prop="customActiveMonthDays">
                  <el-select
                    v-model="form.customActiveMonthDays"
                    multiple
                    clearable
                    placeholder="请选择几号"
                    style="width:400px"
                  >
                    <el-option
                      v-for="dayItem in 31"
                      :key="dayItem"
                      :label="`${dayItem}号`"
                      :value="String(dayItem)"
                    />
                  </el-select>
                </el-form-item>
                <el-tag>设置规则指定日期仅在资源的可用日期内生效</el-tag>
              </el-card>
            </div>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" round @click="hide">取 消</el-button>
        <el-button size="small" round :disable="loading" type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { validateCustomTwoDecimal } from '@/utils/validate'
import {
  addPriceRule,
  updatePriceRule,
  modifyBatchProductParams
} from '../../../api/product'
export default {
  data() {
    /**
       * 校验方法相关
       */
    const validatorPrice = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入价格'))
      } else if (!validateCustomTwoDecimal(value)) {
        callback(new Error('请输入0.01~99999.99范围金额（小数位不超过2位）'))
      } else {
        callback()
      }
    }
    return {
      /**
         * 校验字段相关
         */
      rules: {
        name: [
          {
            required: true,
            message: '请输入规则名'
          }
        ],
        customEffectiveDay: [
          {
            required: true,
            message: '请选择生效日期'
          }
        ],
        priceRuleValue: [
          {
            validator: validatorPrice,
            trigger: ['blur', 'change'],
            required: true
          }
        ],
        dayRule: [
          {
            message: '请选择规则类型',
            required: true
          }
        ],
        customActiveWeekDays: [
          {
            type: 'array',
            required: true,
            message: '请选择周几'
          }
        ],
        customActiveMonthDays: [
          {
            type: 'array',
            required: true,
            message: '请选择每月日期'
          }
        ]
      },
      // 配置
      pickerOptions: {
        // 筛选日期
        disabledDate(time) {
          return time.getTime() < Date.now() - 86400000
        }
      },
      weekOptions: [
        {
          label: '周一',
          value: '2'
        },
        {
          label: '周二',
          value: '3'
        },
        {
          label: '周三',
          value: '4'
        },
        {
          label: '周四',
          value: '5'
        },
        {
          label: '周五',
          value: '6'
        },
        {
          label: '周六',
          value: '7'
        },
        {
          label: '周日',
          value: '1'
        }
      ],
      resolve: null,
      reject: null,
      // 状态组
      loading: false,
      dialogVisible: null,
      // 数据
      mode: 'add',
      productInfo: '',
      form: {
        name: '',
        customActiveWeekDays: [],
        customActiveMonthDays: [],
        customEffectiveDay: '',
        dayRule: 1, //  0日期  1 星期
        priceRuleValue: '',
        productId: ''
      }
    }
  },
  methods: {
    open({ mode = 'add', productInfo, row }) {
      this.mode = mode
      this.form.productId = productInfo.id
      this.productInfo = productInfo
      if (mode === 'edit') {
        const params = Object.assign({}, row)
        if (params.dayRule === 1) {
          params.customActiveWeekDays = params.activeDays.split(',')
          params.customActiveMonthDays = []
        } else {
          params.customActiveMonthDays = params.activeDays.split(',')
          params.customActiveWeekDays = []
        }
        params.customEffectiveDay = [params.beginDay, params.endDay]
        params.priceRuleValue = params.priceRuleValue / 100
        this.form = params
      }
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    close() {
      this.loading = false
      this.$refs.form.resetFields()
    },

    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    /**
       * 按钮组
       */
    // 保存
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const params = Object.assign({}, this.form)
          if (params.dayRule === 1) {
            params.activeDays = params.customActiveWeekDays
              .sort(this.sortNumber)
              .join(',')
          } else {
            params.activeDays = params.customActiveMonthDays
              .sort(this.sortNumber)
              .join(',')
          }
          params.beginDay = params.customEffectiveDay[0]
          params.endDay = params.customEffectiveDay[1]
          params.priceRuleValue = this.$math.mul(params.priceRuleValue, 100, 0)
          delete params.customActiveWeekDays
          delete params.customActiveMonthDays
          this.loading = true
          if (this.mode === 'add') {
            addPriceRule(params)
              .then(res => {
                this.$notify({
                  title: '成功',
                  message: '新增',
                  type: 'success',
                  duration: 2000,
                  offset: 40
                })
                this.resolve && this.resolve()
                this.hide()
              })
              .catch(err => {})
              .finally(() => {
                this.loading = false
              })
          } else {
            updatePriceRule(params)
              .then(res => {
                this.$notify({
                  title: '成功',
                  message: '更新成功',
                  type: 'success',
                  duration: 2000,
                  offset: 40
                })
                this.resolve && this.resolve()
                this.hide()
              })
              .catch(err => {})
              .finally(() => {
                this.loading = false
              })
          }
        }
      })
    },

    // 排序
    sortNumber(a, b) {
      return a - b
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .nest-card-box {
    min-width: 500px;
    width: 100%;
  }
  /* 格式化 */
  .el-radio {
    line-height: 32px;
  }
</style>
